package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.common.Code;
import com.ruan.common.Result;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.service.DepartLocationService;
import com.ruan.service.DepartmentService;
import com.ruan.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DepartLocationMapper departLocationMapper;

    @Autowired
    private DepartLocationService departLocationService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ToolsMapper toolsMapper;



    /**
     * 禁用部门
     * @param id 部门id
     * @return
     */
    @Override
    public boolean stopDepart(Long id) {
        List<Employee> employeeList = getEmployeeList(Math.toIntExact(id));
        if (employeeList.size()>0){
            return false;
        }
        departmentMapper.stopDepart(id);
        return true;
    }

    /**
     * 启用部门
     * @param id 部门id
     * @return
     */
    @Override
    public boolean startDepart(Long id) {
//        List<Employee> employeeList = getEmployeeList(id);
//        if (employeeList!=null){
//            return false;
//        }
        departmentMapper.startDepart(id);
        return true;
    }

    /**
     * 添加部门
     * @param department 前端填写的部门对象
     * @return
     */
    @Override
    public boolean addDepart(Department department) {
//        System.out.println("要插入的部门是："+department);
        String departmentName = department.getName();
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Department::getName,departmentName);
        Integer count = departmentMapper.selectCount(queryWrapper);
        if (count>0){
            return false;
        }
//        department.setEmployeeId(null);//前端选了部门经理
//        department.setManager("暂无");
//        department.setPhone("暂无");
        Employee employee = employeeMapper.selectById(department.getEmployeeId());

        Position position = positionService.getById(employee.getPositionId());
        if(position != null) {
//            employee.setPosition("部门经理");
            employee.setPositionId(Long.valueOf(1));
        }
        LambdaUpdateWrapper<Department> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Department::getId, employee.getDepartmentId())
                .set(Department::getEmployeeId, null)
                .set(Department::getPhone, null); // 设置旧部门经理和手机号为空
        //要更新的实体对象为null，表示不需要更新实体对象，只需要更新符合条件的记录。
        departmentMapper.update(null, updateWrapper);
        //如果新任命的部门经理以前是部门经理，修改旧部门的部门经理为null
        //employee.setDepartmentId(department.getId());//直接调用到新部门//departmentId没传来，需要数据库自动生成，不能set
//        System.out.println("employee.getDepartmentId()是"+employee.getDepartmentId());

        //     初始设置部门主管的phone作为部门的phone
        if(department.getPhone().isBlank()){//isBlank()方法更严格，它不仅检查字符串是否为空，
            // 还会检查字符串是否只包含空格。而isEmpty()方法只检查字符串是否为空或者为null。
            department.setPhone(employee.getPhone());
        }
//        department.setNumber(1);
        departmentMapper.insert(department);//sql自增了部门id,这时候就可以departmentId了
        LambdaQueryWrapper<Department> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Department::getName,departmentName);
        Department department1 = departmentMapper.selectOne(queryWrapper1);
        employee.setDepartmentId(department1.getId());//更新旧该部门经理到新的部门
        employeeMapper.updateById(employee);//更新到数据库
        return true;
    }

    /**
     * 获取部门列表
     * @return
     */
    @Override
    public List<Department> getDepart() {
        LambdaQueryWrapper<Department> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Department::getStatus,"启用");
        List<Department> departmentList = departmentMapper.selectList(queryWrapper);
        return departmentList;
    }

    /**
     * 根据id删除部门和其相关的定位信息
     * @param id 部门id
     * @return
     */
    @Override
    public Result deleteDepart(Long id) {
        LambdaQueryWrapper<Project> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(Project::getDepartmentId, id);
        List<Project> projects = projectMapper.selectList(queryWrapper2);
        if(!projects.isEmpty()){
            return new Result(Code.DELETE_ERR,"该部门还有项目未完成!");
        }

        LambdaQueryWrapper<Tools> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Tools::getDepartmentId, id);
        List<Tools> tools = toolsMapper.selectList(queryWrapper3);
        if(!tools.isEmpty()){
            return new Result(Code.DELETE_ERR,"该部门的工具资源处理好了吗!");
        }
        //删除该部门的定位信息
        LambdaQueryWrapper<DepartLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DepartLocation::getDepartmentId,id);
        DepartLocation departLocation = departLocationMapper.selectOne(queryWrapper);
        if(departLocation!=null){
           departLocationMapper.deleteById(departLocation.getId());
//           System.out.println("该部门的定位信息还在吗？"+departLocationService.getById(departLocation.getId()));
         }

        //删除该部门的相关员工
        LambdaQueryWrapper<Employee> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Employee::getDepartmentId,id);
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper1);
        for(Employee employee : employeeList){
            employeeMapper.deleteById(employee.getId());
        }

        departmentMapper.deleteById(id);
        return new Result(Code.DELETE_OK,"部门删除成功!");
    }

    /**
     * 通过部门id获取当前部门下的员工列表
     * @param id 部门id
     * @return
     */
    private List<Employee> getEmployeeList(Integer id){
        Department department = departmentMapper.selectById(id);
//        String departmentName = department.getName();
        Long departmentId = department.getId();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //---------------------------------------
        queryWrapper.eq(Employee::getDepartmentId,departmentId);
        List<Employee> employeeList = employeeMapper.selectList(queryWrapper);
        return employeeList;
    }
}
